package com.zmj.dubboannotation.consumermobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.zmj.commoncore.dto.ProductCommentDTO;
import com.zmj.dubboannotation.serviceapi.api.MemberService;
import com.zmj.dubboannotation.serviceapi.api.OrderService;
import com.zmj.dubboannotation.serviceapi.api.ProductCommentService;
import com.zmj.dubboannotation.serviceapi.enums.ResultEnum;
import com.zmj.dubboannotation.serviceapi.exception.OrderException;
import com.zmj.dubboannotation.serviceapi.exception.ProductException;
import com.zmj.dubboannotation.serviceapi.model.MallOrder;
import com.zmj.dubboannotation.serviceapi.model.ProductComment;
import com.zmj.dubboannotation.serviceapi.utils.ResultVOUtil;
import com.zmj.dubboannotation.serviceapi.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 商品评论控制层
 * Created by: meijun
 * Date: 2018/10/28 13:41
 */
@RestController
@RequestMapping("/productComment")
@Slf4j
public class ProductCommentController {
    
    @Reference
    private ProductCommentService productCommentService;

    @Reference
    private MemberService memberService;

    @Reference
    private OrderService orderService;

    /**
     * 获取商品评论列表
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping
    public ResultVO get(String productId,Integer pageNum,Integer pageSize) {
        PageInfo<ProductComment> pageInfo = productCommentService.findAllByProductId(productId, pageNum, pageSize);
        return ResultVOUtil.success(pageInfo);
    }

    /**
     * 添加商品評論
     * @param productCommentDTO
     * @return
     */
    @PostMapping
    @ResponseBody
    public ResultVO create(@Valid ProductCommentDTO productCommentDTO) {

        //根据用户id 订单id 查询是否存在该订单
        MallOrder order = new MallOrder();
        order.setId(productCommentDTO.getOrderId());
        order.setMemberId(productCommentDTO.getMemberId());
        List<MallOrder> orderList = orderService.findByQuery(order);
        if(null == orderList || orderList.size() == 0) {
            throw new OrderException(ResultEnum.PRPDUCT_COMMENT_NOT_ORDER);
        }

        //查询该用户 该订单 该商品下是否评价过
        List<ProductComment> list = productCommentService.findByQuery(productCommentDTO);
        if(list != null && list.size() > 0) {
            return ResultVOUtil.error(ResultEnum.PRPDUCT_COMMENT_EXIST);
        }

        productCommentService.save(productCommentDTO);
        return ResultVOUtil.success(ResultEnum.SUCCESS);
    }
    
}
